"""
UI自动化文件系统服务
管理YAML脚本文件和执行报告
"""

import os
import json
import yaml
import shutil
import subprocess
import asyncio
from pathlib import Path
from typing import List, Dict, Any, Optional
from datetime import datetime
from sqlalchemy.orm import Session

def _clean_options(options: Dict[str, Any]) -> Dict[str, Any]:
    """清理执行选项，移除空值"""
    if not options:
        return {}
    
    cleaned = {}
    for key, value in options.items():
        # 跳过空字符串、None、False（但保留0）
        if value == "" or value is None:
            continue
        if isinstance(value, bool) and not value:
            continue
        cleaned[key] = value
    
    return cleaned
from ..models.ui_automation import UiAutomationScript
from ..core.config import settings


class UiFileService:
    """UI自动化文件系统服务"""

    def __init__(self):
        # 获取项目根目录
        self.project_root = Path(__file__).parent.parent.parent.parent
        self.ui_test_dir = self.project_root / "ui-test"
        self.scripts_dir = self.ui_test_dir / "scripts"
        # reports目录已移除，使用midscene_run/report
        self.reports_dir = self.ui_test_dir / "midscene_run" / "report"
        self.output_dir = self.ui_test_dir / "midscene_run" / "output"
        self.temp_dir = self.ui_test_dir / "temp"
        
        # 确保目录存在
        self._ensure_directories()

    def _ensure_directories(self):
        """确保必要目录存在"""
        for directory in [self.ui_test_dir, self.scripts_dir, self.temp_dir]:
            directory.mkdir(parents=True, exist_ok=True)

    def get_script_file_path(self, script_id: int) -> Path:
        """获取脚本文件路径"""
        return self.scripts_dir / f"script_{script_id}.yaml"

    def get_temp_script_path(self, execution_id: int) -> Path:
        """获取临时脚本文件路径"""
        return self.temp_dir / f"execution_{execution_id}.yaml"

    def save_script_to_file(self, script: UiAutomationScript) -> str:
        """将脚本保存到文件系统"""
        file_path = self.get_script_file_path(script.id)
        
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(script.yaml_content)
            return str(file_path)
        except Exception as e:
            raise Exception(f"保存脚本文件失败: {str(e)}")

    def read_script_from_file(self, script_id: int) -> Optional[str]:
        """从文件系统读取脚本内容"""
        file_path = self.get_script_file_path(script_id)
        
        if not file_path.exists():
            return None
            
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return f.read()
        except Exception as e:
            raise Exception(f"读取脚本文件失败: {str(e)}")

    async def create_temp_script_file(self, yaml_content: str, execution_name: str) -> Path:
        """创建临时脚本文件用于执行"""
        temp_dir = self.ui_test_dir / "temp"
        temp_dir.mkdir(exist_ok=True)
        
        temp_file = temp_dir / f"{execution_name}.yaml"
        
        try:
            with open(temp_file, 'w', encoding='utf-8') as f:
                f.write(yaml_content)
                
            return temp_file
        except Exception as e:
            raise Exception(f"创建临时脚本文件失败: {str(e)}")

    def delete_script_file(self, script_id: int) -> bool:
        """删除脚本文件"""
        file_path = self.get_script_file_path(script_id)
        
        try:
            if file_path.exists():
                file_path.unlink()
            return True
        except Exception as e:
            print(f"删除脚本文件失败: {str(e)}")
            return False

    def create_execution_file(self, execution_id: int, yaml_content: str) -> str:
        """为执行创建临时脚本文件"""
        file_path = self.get_temp_script_path(execution_id)
        
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(yaml_content)
            return str(file_path)
        except Exception as e:
            raise Exception(f"创建执行文件失败: {str(e)}")

    def cleanup_execution_file(self, execution_id: int):
        """清理执行文件"""
        file_path = self.get_temp_script_path(execution_id)
        try:
            if file_path.exists():
                file_path.unlink()
        except Exception as e:
            print(f"清理执行文件失败: {str(e)}")

    async def execute_midscene_script(
        self, 
        script_file: str, 
        options: Dict[str, Any] = None
    ) -> Dict[str, Any]:
        """
        执行Midscene脚本
        """
        try:
            # 构建命令
            cmd = ["midscene", script_file]
            
            # 打印执行信息
            print(f"[Midscene] 执行脚本文件: {script_file}")
            print(f"[Midscene] 工作目录: {self.ui_test_dir}")
            print(f"[Midscene] 执行选项: {options}")
            
            # 清理并添加所有支持的Midscene选项
            options = _clean_options(options)
            
            # 默认使用配置文件（如果用户没有指定的话）
            if not options or not options.get("config"):
                config_path = self.ui_test_dir / "midscene.config.yaml"
                if config_path.exists():
                    cmd.extend(["--config", str(config_path)])
                    print(f"[Midscene] 使用默认配置文件: {config_path}")
            
            if options:
                # 执行控制选项
                if options.get("concurrent"):
                    cmd.extend(["--concurrent", str(options["concurrent"])])
                if options.get("continueOnError"):
                    cmd.append("--continue-on-error")
                if options.get("shareBrowserContext"):
                    cmd.append("--share-browser-context")
                if options.get("summary"):
                    cmd.extend(["--summary", options["summary"]])
                
                # 浏览器选项
                if options.get("headed"):
                    cmd.append("--headed")
                if options.get("keepWindow"):
                    cmd.append("--keep-window")
                
                # 配置文件
                if options.get("config"):
                    cmd.extend(["--config", options["config"]])
                
                # Web选项
                if options.get("userAgent"):
                    cmd.extend(["--web.userAgent", options["userAgent"]])
                if options.get("viewportWidth"):
                    cmd.extend(["--web.viewportWidth", str(options["viewportWidth"])])
                if options.get("viewportHeight"):
                    cmd.extend(["--web.viewportHeight", str(options["viewportHeight"])])
                
                # Android选项
                if options.get("androidDeviceId"):
                    cmd.extend(["--android.deviceId", options["androidDeviceId"]])
                
                # 环境变量选项
                if options.get("dotenvDebug"):
                    cmd.append("--dotenv-debug")
                if options.get("dotenvOverride"):
                    cmd.append("--dotenv-override")

            # 执行命令
            process = await asyncio.create_subprocess_exec(
                *cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=str(self.ui_test_dir),
                env=os.environ.copy()
            )

            stdout, stderr = await process.communicate()
            
            # 解码输出
            stdout_text = stdout.decode('utf-8')
            stderr_text = stderr.decode('utf-8')
            
            # 打印执行结果
            print(f"[Midscene] 命令执行完成，返回码: {process.returncode}")
            if stdout_text:
                print(f"[Midscene] 标准输出:\n{stdout_text}")
            if stderr_text:
                print(f"[Midscene] 错误输出:\n{stderr_text}")

            return {
                "success": process.returncode == 0,
                "returncode": process.returncode,
                "stdout": stdout_text,
                "stderr": stderr_text,
                "command": " ".join(cmd)
            }

        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "command": " ".join(cmd) if 'cmd' in locals() else ""
            }

    async def execute_midscene_script_stream(
        self, 
        script_file: str, 
        options: Dict[str, Any] = None,
        execution_id: int = None
    ):
        """
        流式执行Midscene脚本，实时yield输出
        """
        try:
            # 构建命令 - 单个执行不使用配置文件
            cmd = ["midscene", script_file]
            
            # 清理并添加所有支持的Midscene选项
            options = _clean_options(options)
            
            # 默认添加--headed参数用于单个执行
            cmd.append("--headed")

            if options:
                # 添加所有Midscene选项（复用之前的逻辑）
                if options.get("concurrent"):
                    cmd.extend(["--concurrent", str(options["concurrent"])])
                
                if options.get("continueOnError"):
                    cmd.append("--continue-on-error")
                
                if options.get("shareBrowserContext"):
                    cmd.append("--share-browser-context")
                
                if options.get("summary"):
                    cmd.extend(["--summary", options["summary"]])
                
                if options.get("headed"):
                    cmd.append("--headed")
                
                if options.get("keepWindow"):
                    cmd.append("--keep-window")
                
                if options.get("config"):
                    cmd.extend(["--config", options["config"]])
                
                if options.get("userAgent"):
                    cmd.extend(["--web.userAgent", options["userAgent"]])
                
                if options.get("viewportWidth"):
                    cmd.extend(["--web.viewportWidth", str(options["viewportWidth"])])
                
                if options.get("viewportHeight"):
                    cmd.extend(["--web.viewportHeight", str(options["viewportHeight"])])
                
                if options.get("androidDeviceId"):
                    cmd.extend(["--android.deviceId", options["androidDeviceId"]])
                
                if options.get("dotenvDebug"):
                    cmd.append("--dotenv-debug")

                if options.get("dotenvOverride"):
                    cmd.append("--dotenv-override")

            # 输出执行命令和后端日志
            cmd_str = ' '.join(cmd)
            print(f"[Backend] 执行Midscene命令: {cmd_str}")
            print(f"[Backend] 工作目录: {self.ui_test_dir}")
            yield {"type": "command", "message": f"执行命令: {cmd_str}"}

            # 执行命令
            print(f"[Backend] 启动异步进程...")
            # 构建环境变量：优先使用ui-test/.env配置，确保AI模型配置正确
            import os
            from dotenv import dotenv_values
            
            # 从系统环境变量开始
            env = os.environ.copy()
            
            # 加载ui-test目录下的.env文件，覆盖系统环境变量
            ui_test_env_file = self.ui_test_dir / ".env"
            if ui_test_env_file.exists():
                ui_test_env = dotenv_values(ui_test_env_file)
                env.update(ui_test_env)  # 直接覆盖，确保使用正确的AI配置
            
            print(f"[Backend] 开始执行Midscene")
            
            process = await asyncio.create_subprocess_exec(
                *cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=str(self.ui_test_dir),
                env=env
            )
            print(f"[Backend] 进程已启动，PID: {process.pid}")
            
            # 存储进程引用（如果提供了execution_id）
            if execution_id:
                # 导入服务类来存储进程引用
                from .ui_automation_service import UiAutomationService
                UiAutomationService._execution_processes[execution_id] = process

            # 简化的流式输出读取
            stdout_done = False
            stderr_done = False
            
            while not stdout_done or not stderr_done:
                try:
                    # 读取stdout
                    if not stdout_done and process.stdout:
                        try:
                            line = await asyncio.wait_for(process.stdout.readline(), timeout=0.1)
                            if line:
                                line_text = line.decode('utf-8').strip()
                                if line_text:
                                    yield {"type": "stdout", "message": line_text}
                            else:
                                stdout_done = True
                        except asyncio.TimeoutError:
                            pass
                    
                    # 读取stderr
                    if not stderr_done and process.stderr:
                        try:
                            line = await asyncio.wait_for(process.stderr.readline(), timeout=0.1)
                            if line:
                                line_text = line.decode('utf-8').strip()
                                if line_text:
                                    yield {"type": "stderr", "message": line_text}
                            else:
                                stderr_done = True
                        except asyncio.TimeoutError:
                            pass
                    
                    # 检查进程是否结束
                    if process.returncode is not None:
                        break
                        
                except Exception as e:
                    yield {"type": "error", "message": f"读取输出失败: {str(e)}"}
                    break

            # 等待进程完成
            await process.wait()
            print(f"[Backend] 进程执行完成，返回码: {process.returncode}")
            
            # 清理进程引用
            if execution_id:
                from .ui_automation_service import UiAutomationService
                UiAutomationService._execution_processes.pop(execution_id, None)
            
            yield {
                "type": "complete", 
                "message": f"执行完成，返回码: {process.returncode}",
                "returncode": process.returncode,
                "success": process.returncode == 0
            }

        except Exception as e:
            # 清理进程引用
            if execution_id:
                from .ui_automation_service import UiAutomationService
                UiAutomationService._execution_processes.pop(execution_id, None)
            
            yield {
                "type": "error", 
                "message": f"执行失败: {str(e)}",
                "success": False
            }

    async def execute_multiple_scripts(
        self, 
        script_pattern: str, 
        options: Dict[str, Any] = None
    ) -> Dict[str, Any]:
        """
        批量执行多个脚本（使用通配符模式）
        """
        try:
            # 构建命令 - 直接使用通配符模式，不需要--files
            cmd = ["midscene", script_pattern]
            
            # 清理并添加所有支持的Midscene选项
            options = _clean_options(options)
            if options:
                # 执行控制选项
                if options.get("concurrent"):
                    cmd.extend(["--concurrent", str(options["concurrent"])])
                if options.get("continueOnError"):
                    cmd.append("--continue-on-error")
                if options.get("shareBrowserContext"):
                    cmd.append("--share-browser-context")
                if options.get("summary"):
                    cmd.extend(["--summary", options["summary"]])
                
                # 浏览器选项
                if options.get("headed"):
                    cmd.append("--headed")
                if options.get("keepWindow"):
                    cmd.append("--keep-window")
                
                # 配置文件
                if options.get("config"):
                    cmd.extend(["--config", options["config"]])
                
                # Web选项
                if options.get("userAgent"):
                    cmd.extend(["--web.userAgent", options["userAgent"]])
                if options.get("viewportWidth"):
                    cmd.extend(["--web.viewportWidth", str(options["viewportWidth"])])
                if options.get("viewportHeight"):
                    cmd.extend(["--web.viewportHeight", str(options["viewportHeight"])])
                
                # Android选项
                if options.get("androidDeviceId"):
                    cmd.extend(["--android.deviceId", options["androidDeviceId"]])
                
                # 环境变量选项
                if options.get("dotenvDebug"):
                    cmd.append("--dotenv-debug")
                if options.get("dotenvOverride"):
                    cmd.append("--dotenv-override")

            # 执行命令
            process = await asyncio.create_subprocess_exec(
                *cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=str(self.ui_test_dir),
                env=os.environ.copy()
            )

            stdout, stderr = await process.communicate()
            
            # 解码输出
            stdout_text = stdout.decode('utf-8')
            stderr_text = stderr.decode('utf-8')
            
            # 打印执行结果
            print(f"[Midscene] 命令执行完成，返回码: {process.returncode}")
            if stdout_text:
                print(f"[Midscene] 标准输出:\n{stdout_text}")
            if stderr_text:
                print(f"[Midscene] 错误输出:\n{stderr_text}")

            return {
                "success": process.returncode == 0,
                "returncode": process.returncode,
                "stdout": stdout_text,
                "stderr": stderr_text,
                "command": " ".join(cmd)
            }

        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "command": " ".join(cmd) if 'cmd' in locals() else ""
            }

    async def execute_scripts_with_files_param(
        self, 
        script_files: List[str], 
        options: Dict[str, Any] = None
    ) -> Dict[str, Any]:
        """
        使用--files参数执行多个脚本文件
        """
        try:
            # 构建命令 - 使用--files参数指定文件列表
            cmd = ["midscene", "--files"] + script_files
            
            # 清理并添加所有支持的Midscene选项
            options = _clean_options(options)
            if options:
                # 执行控制选项
                if options.get("concurrent"):
                    cmd.extend(["--concurrent", str(options["concurrent"])])
                if options.get("continueOnError"):
                    cmd.append("--continue-on-error")
                if options.get("shareBrowserContext"):
                    cmd.append("--share-browser-context")
                if options.get("summary"):
                    cmd.extend(["--summary", options["summary"]])
                
                # 浏览器选项
                if options.get("headed"):
                    cmd.append("--headed")
                if options.get("keepWindow"):
                    cmd.append("--keep-window")
                
                # 配置文件
                if options.get("config"):
                    cmd.extend(["--config", options["config"]])
                
                # Web选项
                if options.get("userAgent"):
                    cmd.extend(["--web.userAgent", options["userAgent"]])
                if options.get("viewportWidth"):
                    cmd.extend(["--web.viewportWidth", str(options["viewportWidth"])])
                if options.get("viewportHeight"):
                    cmd.extend(["--web.viewportHeight", str(options["viewportHeight"])])
                
                # Android选项
                if options.get("androidDeviceId"):
                    cmd.extend(["--android.deviceId", options["androidDeviceId"]])
                
                # 环境变量选项
                if options.get("dotenvDebug"):
                    cmd.append("--dotenv-debug")
                if options.get("dotenvOverride"):
                    cmd.append("--dotenv-override")

            # 执行命令
            process = await asyncio.create_subprocess_exec(
                *cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=str(self.ui_test_dir),
                env=os.environ.copy()
            )

            stdout, stderr = await process.communicate()
            
            # 解码输出
            stdout_text = stdout.decode('utf-8')
            stderr_text = stderr.decode('utf-8')
            
            # 打印执行结果
            print(f"[Midscene] 命令执行完成，返回码: {process.returncode}")
            if stdout_text:
                print(f"[Midscene] 标准输出:\n{stdout_text}")
            if stderr_text:
                print(f"[Midscene] 错误输出:\n{stderr_text}")

            return {
                "success": process.returncode == 0,
                "returncode": process.returncode,
                "stdout": stdout_text,
                "stderr": stderr_text,
                "command": " ".join(cmd)
            }

        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "command": " ".join(cmd) if 'cmd' in locals() else ""
            }

    def get_execution_reports(self, execution_id: int) -> Dict[str, Any]:
        """获取执行报告"""
        # Midscene报告在ui-test/midscene_run/report目录
        report_dir = self.ui_test_dir / "midscene_run" / "report"
        
        reports = {
            "summary": None,
            "detailed_reports": [],
            "screenshots": [],
            "html_reports": [],
            "report_dir": str(report_dir) if report_dir.exists() else None
        }

        if not report_dir.exists():
            return reports

        try:
            # 查找汇总报告
            summary_file = report_dir / "summary.json"
            if summary_file.exists():
                with open(summary_file, 'r', encoding='utf-8') as f:
                    reports["summary"] = json.load(f)

            # 查找HTML报告文件
            for file_path in report_dir.rglob("*.html"):
                stat = file_path.stat()
                reports["html_reports"].append({
                    "name": file_path.name,
                    "path": str(file_path),
                    "relative_path": str(file_path.relative_to(report_dir)),
                    "size": stat.st_size,
                    "mtime": stat.st_mtime
                })

            # 查找详细报告文件
            for file_path in report_dir.rglob("*.json"):
                if file_path.name != "summary.json":
                    reports["detailed_reports"].append({
                        "name": file_path.name,
                        "path": str(file_path),
                        "relative_path": str(file_path.relative_to(report_dir))
                    })

            # 查找截图文件
            for ext in ["*.png", "*.jpg", "*.jpeg"]:
                for file_path in report_dir.rglob(ext):
                    reports["screenshots"].append({
                        "name": file_path.name,
                        "path": str(file_path),
                        "relative_path": str(file_path.relative_to(report_dir))
                    })

        except Exception as e:
            reports["error"] = str(e)

        return reports

    def get_script_reports_history(self, script_id: int) -> List[Dict[str, Any]]:
        """获取脚本的历史报告 - 已简化，只返回最新报告"""
        # 历史报告功能已简化，用户可以直接查看ui-test/midscene_run/report的最新报告
        # 不再维护历史报告归档，避免创建reports目录
        return []

    def archive_execution_report(self, execution_id: int, script_id: int):
        """归档执行报告 - 已禁用，不再自动创建reports目录"""
        # 归档功能已禁用，避免自动创建reports目录
        # 用户可以直接在ui-test/midscene_run/report目录查看最新报告
        pass

    def list_all_scripts(self) -> List[Dict[str, Any]]:
        """列出所有脚本文件"""
        scripts = []
        
        try:
            for yaml_file in self.scripts_dir.glob("*.yaml"):
                try:
                    with open(yaml_file, 'r', encoding='utf-8') as f:
                        content = f.read()
                        # 尝试解析YAML获取基本信息
                        try:
                            parsed = yaml.safe_load(content)
                            title = parsed.get('title', yaml_file.stem)
                        except:
                            title = yaml_file.stem
                    
                    scripts.append({
                        "file_name": yaml_file.name,
                        "file_path": str(yaml_file),
                        "title": title,
                        "size": yaml_file.stat().st_size,
                        "modified_time": datetime.fromtimestamp(yaml_file.stat().st_mtime)
                    })
                except Exception as e:
                    print(f"读取脚本文件 {yaml_file} 失败: {str(e)}")

        except Exception as e:
            print(f"列出脚本文件失败: {str(e)}")

        return scripts

    def validate_midscene_installation(self) -> Dict[str, Any]:
        """验证Midscene是否已安装"""
        try:
            result = subprocess.run(
                ["midscene", "--version"],
                capture_output=True,
                text=True,
                timeout=10
            )
            
            return {
                "installed": result.returncode == 0,
                "version": result.stdout.strip() if result.returncode == 0 else None,
                "error": result.stderr if result.returncode != 0 else None
            }
        except subprocess.TimeoutExpired:
            return {"installed": False, "error": "命令执行超时"}
        except FileNotFoundError:
            return {"installed": False, "error": "Midscene未安装"}
        except Exception as e:
            return {"installed": False, "error": str(e)}

    def find_execution_result_json(self, execution_name: str) -> Optional[Dict[str, Any]]:
        """
        根据执行名称查找对应的结果JSON文件
        execution_name格式: execution_{execution_id}
        """
        try:
            if not self.output_dir.exists():
                print(f"[Backend] Output目录不存在: {self.output_dir}")
                return None
            
            # 查找最新的匹配JSON文件
            # JSON文件中的script路径格式: "../../temp/execution_{execution_id}.yaml"
            latest_file = None
            latest_time = 0
            
            for json_file in self.output_dir.glob("summary-*.json"):
                try:
                    import json as json_module
                    with open(json_file, 'r', encoding='utf-8') as f:
                        data = json_module.load(f)
                    
                    # 检查results中是否有匹配的script
                    if 'results' in data:
                        for result in data['results']:
                            script_path = result.get('script', '')
                            # script路径格式: "../../temp/execution_{execution_id}.yaml"
                            # 精确匹配：确保脚本名称完全一致
                            script_filename = script_path.split('/')[-1] if '/' in script_path else script_path
                            expected_filename = f"{execution_name}.yaml"
                            
                            if script_filename == expected_filename:
                                # 获取文件修改时间
                                file_time = json_file.stat().st_mtime
                                if file_time > latest_time:
                                    latest_time = file_time
                                    latest_file = json_file
                                    data['_json_file_path'] = str(json_file)
                                    print(f"[Backend] 找到匹配的JSON文件: {json_file}, 脚本: {script_filename}")
                                    return data
                                
                except Exception as e:
                    print(f"[Backend] 读取JSON文件失败 {json_file}: {str(e)}")
                    continue
            
            if latest_file:
                print(f"[Backend] 找到结果文件: {latest_file}")
            else:
                print(f"[Backend] 未找到执行名称为 {execution_name} 的结果文件")
                
            return None
                
        except Exception as e:
            print(f"[Backend] 查找执行结果JSON失败: {str(e)}")
            return None

    def parse_execution_result(self, result_json: Dict[str, Any], execution_name: str) -> Dict[str, Any]:
        """
        解析执行结果JSON，提取关键信息
        """
        try:
            summary = result_json.get('summary', {})
            results = result_json.get('results', [])
            
            # 查找当前执行的结果 - 精确匹配脚本名称
            current_result = None
            expected_filename = f"{execution_name}.yaml"
            
            for result in results:
                script_path = result.get('script', '')
                script_filename = script_path.split('/')[-1] if '/' in script_path else script_path
                
                if script_filename == expected_filename:
                    current_result = result
                    print(f"[Backend] 找到匹配的执行结果: {script_filename}")
                    break
            
            if not current_result:
                print(f"[Backend] 在结果中未找到当前执行: {execution_name}")
                return {}
            
            parsed_result = {
                'total_count': summary.get('total', 1),
                'success_count': 1 if current_result.get('success', False) else 0,
                'failed_count': 0 if current_result.get('success', False) else 1,
                'duration_ms': current_result.get('duration', 0),  # 毫秒
                'duration_seconds': int(current_result.get('duration', 0) / 1000),  # 转换为秒
                'success': current_result.get('success', False),
                'report_file': current_result.get('report', ''),
                'result_json_path': result_json.get('_json_file_path', ''),
                'generated_at': summary.get('generatedAt', ''),
                'full_result_data': result_json  # 完整的JSON数据
            }
            
            print(f"[Backend] 解析执行结果成功: {parsed_result}")
            return parsed_result
            
        except Exception as e:
            print(f"[Backend] 解析执行结果失败: {str(e)}")
            return {}
